package com.uenpay.im.ui.old.activity.phonebook;

import android.text.TextUtils;

import com.qiyunxin.android.http.listener.OnHttpRequestTextListener;
import com.qiyunxin.android.http.net.HttpInvokeItem;
import com.qiyunxin.android.http.net.HttpRequestAsyncTaskQueue;
import com.qiyunxin.android.http.net.HttpRequestType;
import com.qiyunxin.android.http.net.HttpTextAsyncTask;
import com.qyx.android.weight.contacts.ContactEntity;
import com.uenpay.im.IMApplication;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * @author SL
 * @created 2016-2-26 下午4:06:42
 * @copyRight http://www.qiyunxin.com
 * @function 手机联系人管理
 */
public class PhoneBookHandle {

	public interface IUploadContactsResultListener {
		void onUploadContactsResult(int status, String msg,
													ArrayList<MobileContatcsEntity> arrayList);
	}

	/**
	 * 上传联系人
	 *
	 * @param allContacts
	 */
	public void uploadContactsByPhoneBook(
			final ArrayList<ContactEntity> allContacts,
			final IUploadContactsResultListener mIUploadContactsResultListener) {
		String mobiles = getContactsMobiles(allContacts);
		UploadContactsByPhoneBookInvokeItem item = new UploadContactsByPhoneBookInvokeItem(
				mobiles);
		HttpRequestAsyncTaskQueue
				.getInstance()
				.AddTask(
						new HttpTextAsyncTask(item)
								.SetRequestType(HttpRequestType.SERVER_ONLY),
						new OnHttpRequestTextListener() {

							@Override
							public void OnFail(boolean isCache, String reason) {
								mIUploadContactsResultListener
										.onUploadContactsResult(-1, "", null);
							}

							@Override
							public void OnProgress(long total_bytes,
									long downloaded_bytes) {
							}

							@Override
							public void OnSuccess(HttpInvokeItem item,
									boolean isCache, String cacheFilePath) {
								final UploadContactsByPhoneBookInvokeItem.UploadContactsByPhoneBookInvokeItemResult result = ((UploadContactsByPhoneBookInvokeItem) item)
										.getOutPut();
								if (result != null && result.arrayList != null) {
									mIUploadContactsResultListener
											.onUploadContactsResult(
													result.status,
													result.msg,
													getMobileContatcsEntitys(
															allContacts,
															result.arrayList));
								} else if (result != null) {
									mIUploadContactsResultListener
											.onUploadContactsResult(
													result.status, result.msg,
													null);
								} else {
									mIUploadContactsResultListener
											.onUploadContactsResult(-1, "",
													null);
								}
							}
						});

	}

	public interface IInvitationResultListener {
		void onResultListener(int status, String msg);
	}

	/**
	 * 邀请
	 *
	 * @param username
	 */
	public void invitationContacts(String username,
			final IInvitationResultListener mIInvitationResultListener) {
		InvitationContactsByPhoneBookInvokeItem item = new InvitationContactsByPhoneBookInvokeItem(
				username);
		HttpRequestAsyncTaskQueue
				.getInstance()
				.AddTask(
						new HttpTextAsyncTask(item)
								.SetRequestType(HttpRequestType.SERVER_ONLY),
						new OnHttpRequestTextListener() {

							@Override
							public void OnFail(boolean isCache, String reason) {
								mIInvitationResultListener.onResultListener(-1,
										reason);
							}

							@Override
							public void OnProgress(long total_bytes,
									long downloaded_bytes) {
							}

							@Override
							public void OnSuccess(HttpInvokeItem item,
									boolean isCache, String cacheFilePath) {
								final InvitationContactsByPhoneBookInvokeItem.InvitationContactsByPhoneBookInvokeItemResult result = ((InvitationContactsByPhoneBookInvokeItem) item)
										.getOutPut();
								if (result != null) {
									mIInvitationResultListener
											.onResultListener(result.status,
													result.msg);
								} else {
									mIInvitationResultListener
											.onResultListener(-1, "");
								}
							}
						});

	}

	/**
	 * 获取联系人手机号
	 *
	 * @param allContacts
	 * @return
	 */
	public String getContactsMobiles(ArrayList<ContactEntity> allContacts) {
		String mobiles = "";
		for (int i = 0, size = allContacts.size(); i < size; i++) {
			if (TextUtils.isEmpty(mobiles)) {
				mobiles = allContacts.get(i).mobilePhone;
			} else {
				mobiles = mobiles + "," + allContacts.get(i).mobilePhone;
			}
		}
		mobiles = mobiles.replace(" ", "");
		return mobiles;
	}

	/**
	 * 获取联系人实例
	 *
	 * @return
	 */
	public ArrayList<MobileContatcsEntity> getMobileContatcsEntitys(
			ArrayList<ContactEntity> allContacts,
			ArrayList<MobileContatcsEntity> serviceArrayList) {
		ArrayList<MobileContatcsEntity> arrayList = new ArrayList<MobileContatcsEntity>();
		ArrayList<MobileContatcsEntity> notFriendsList = new ArrayList<MobileContatcsEntity>();
		for (int i = 0, size = allContacts.size(); i < size; i++) {
			for (int j = 0, length = serviceArrayList.size(); j < length; j++) {
				if (TextUtils.isEmpty(allContacts.get(i).mobilePhone)) {
					continue;
				}
				String mobile = allContacts.get(i).mobilePhone.replace(" ", "");
				if (mobile.equals(serviceArrayList.get(j).mobilePhone)) {
					MobileContatcsEntity mMobileContatcsEntity = new MobileContatcsEntity();
					mMobileContatcsEntity.custId = serviceArrayList.get(j).custId;
					mMobileContatcsEntity.nickName = serviceArrayList.get(j).nickName;
					mMobileContatcsEntity.name = allContacts.get(i).name;
					mMobileContatcsEntity.mobilePhone = allContacts.get(i).mobilePhone;
					mMobileContatcsEntity._isfriend = serviceArrayList.get(j)._isfriend;
					mMobileContatcsEntity._invited = serviceArrayList.get(j)._invited;
					if (mMobileContatcsEntity._isfriend == 1) {
						arrayList.add(arrayList.size(), mMobileContatcsEntity);
					} else if (TextUtils.isEmpty(mMobileContatcsEntity.custId)
							&& mMobileContatcsEntity._isfriend == 0) {
						arrayList.add(0, mMobileContatcsEntity);
					} else if (!TextUtils.isEmpty(mMobileContatcsEntity.custId)
							&& mMobileContatcsEntity._isfriend == 0) {
						notFriendsList.add(mMobileContatcsEntity);
					}
					break;
				}
			}
		}
		if (notFriendsList.size() > 0) {
			arrayList.addAll(0, notFriendsList);
		}
		saveFriends(arrayList);
		return arrayList;
	}

	/**
	 * 将好友数据保存在本地
	 *
	 * @param arrayList
	 */
	public void saveFriends(ArrayList<MobileContatcsEntity> arrayList) {
		JSONArray contactsArr = new JSONArray();
		for (int i = 0, size = arrayList.size(); i < size; i++) {
			JSONObject json = new JSONObject();
			try {
				json.put("name", arrayList.get(i).name);
				json.put("nickname", arrayList.get(i).nickName);
				json.put("_isfriend", arrayList.get(i)._isfriend);
				json.put("_invited", arrayList.get(i)._invited);
				json.put("custid", arrayList.get(i).custId);
				json.put("mobilephone", arrayList.get(i).mobilePhone);
				contactsArr.put(json);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (contactsArr != null && contactsArr.length() > 0) {
			IMApplication.config.setContactsJson(contactsArr.toString());
		}
	}
}
